<?php
namespace Kuoqi\Dom{
class DomElement{
	public $actElement;
	public $nodeValue;
	public $parent = null;
	public function __construct($str){
		if(is_object($str)){
			if(get_class($str)==get_class($this)){
				$this->actElement = $str->actElement;
				$this->parent = $str->parent;
			}else{
				$this->actElement = $str;
				$this->parent = $this->actElement->parentNode;	
			}
		}else{
			//$this->actElement = new DomElement($str);
		}
	}
	
	//find
	public function find($selector){
		$selector = DomTools::getSelector($selector);
		$nodelist = new DomNodelist();
		if(!$this->actElement){return $nodelist;}
		$nodes = $this->actElement->getElementsByTagName($selector['tagname']);
		foreach($nodes as $vv){
			$hasit = 1;
			//判定元素ID
			if($selector['id']){
				$isid = $vv->getAttribute('id');
				if($isid!=$selector){
					$hasit *= 0;	
				}
			}
			//判定元素是否有class
			if($selector['class']){
				$iscls = $vv->getAttribute('class');
				$iscls = explode(' ',$iscls);
				foreach($selector['class'] as $av){
					if(!in_array($av,$iscls)){
						$hasit *= 0;
					}
				}
			}
			//判定元素是否有该属性
			if($selector['attr']){
				foreach($selector['attr'] as $ak=>$av){
					if($vv->getAttribute($ak)!=$av){
						$hasit *= 0;	
					}
				}
			}
			if($hasit){
				$nodelist->push($vv);
			}
		}
		return $nodelist;	
	}
	public function getAttr($attrName){
		return $this->getAttribute($attrName);
	}
	public function getAttribute($attrName){
		return $this->actElement?$this->actElement->getAttribute($attrName):NULL;
	}
	public function setAttr($attrName,$attrVal){
		return $this->setAttribute($attrName,$attrVal);
	}
	public function setAttribute($attrName,$attrVal){
		return $this->actElement?$this->actElement->setAttribute($attrName,$attrVal):NULL;
	}
	public function removeAttr($attrName){
		return $this->removeAttribute($attrName);
	}
	public function removeAttribute($attrName){
		return $this->actElement?$this->actElement->removeAttribute($attrName):NULL;
	}
	//删除自己
	public function remove(){
		$this->parent->removeChild($this->actElement);
	}
	public function children(){
			
	}
	//获取文本内容
	public function text(){
		return $this->actElement?$this->actElement->nodeValue:NULL;	
	}
	//获取文本内容
	public function getText(){
		return $this->actElement?$this->actElement->nodeValue:NULL;		
	}
	
	public function innerHtml(){
	    $innerHTML = '';
		$children = $this->actElement->childNodes; 
		foreach ($children as $child) { 
		 	$innerHTML .= $child->ownerDocument->saveXML( $child ); 
		} 
		return $innerHTML; 
	}
}}